<template>
  <div class="cesium-draw">
    <div id="cesium-drawer" />
    <div class="mouse-postion">{{ nowPostion.wgs84 }}</div>
    <div class="tool-box">
      <div class="slider-box-wrapper"><slider-box v-model:value="viewModel.backgroundTransparency" :max="1" @change="change" /></div>
      <div class="slider-box-wrapper"><slider-box v-model:value="viewModel.bandTransparency" :max="1" @change="change" /></div>
      <div class="slider-box-wrapper"><slider-box v-model:value="viewModel.bandThickness" :max="100" :step="0.1" @change="change" /></div>
      <div class="slider-box-wrapper"><slider-box v-model:value="viewModel.band1Position" :max="7000" :step="1" @change="change" /></div>
      <div class="slider-box-wrapper"><slider-box v-model:value="viewModel.band2Position" :max="7500" :step="1" @change="change" /></div>
      <div class="slider-box-wrapper"><slider-box v-model:value="viewModel.band3Position" :max="8000" :step="1" @change="change" /></div>
      <div class="select-box-wrapper"><a-checkbox v-model:checked="viewModel.gradient" @change="change">gradient</a-checkbox></div>
      <!-- <div class="select-box-wrapper"><select-box :options="locationToolbarOptions" /></div>
      <div class="select-box-wrapper"><select-box :options="entityToolbarOptions" /></div>
      <div class="select-box-wrapper"><select-box :options="sizeOptions" /></div>
      <div class="select-box-wrapper"><a-checkbox v-model:checked="softShadows">soft shadows</a-checkbox></div>
      <div class="select-box-wrapper"><a-checkbox v-model:checked="terrainShadows">terrain shadows</a-checkbox></div>
      <div class="select-box-wrapper"><a-checkbox v-model:checked="entityShadows">entity shadows</a-checkbox></div> -->
      <div id="menu">
        <p><button @click="onClick('play')">播放</button></p>
        <p><button @click="onClick('stop')">暂停</button></p>
      </div>
    </div>
  </div>
</template>

<script>
//参考：https://sandcastle.cesium.com/?src=Fog%20Post%20Process.html
import { DownOutlined, EditOutlined } from '@ant-design/icons-vue';
import { defineComponent, ref, watch } from 'vue';
import SliderBox from '@components/widgets/slider-box';
import SelectBox from '@components/widgets/select-box';
import * as Cesium from '@cesium/Source/Cesium.js';
import MousePosition from '@functional/utils/mousePosition';

export default defineComponent({
  name: 'contour', // 等值线
  components: { DownOutlined, EditOutlined, SliderBox, SelectBox },
  setup() {
    return {
      viewer: null,
      updateMaterial: () => {}
    };
  },
  data() {
    return {
      nowPostion: {},
      viewModel: {
        gradient: false,
        band1Position: 7000.0,
        band2Position: 7500.0,
        band3Position: 8000.0,
        bandThickness: 100.0,
        bandTransparency: 0.5,
        backgroundTransparency: 0.75
      }
    };
  },
  computed: {},
  watch: {
    viewModel(model) {
      console.log(model);
      // this.viewer && this.updateMaterial();
    }
  },
  mounted() {
    this.initViewer();
  },
  beforeUnmount() {
    if (this.viewer) {
      this.viewer.destroy();
      this.viewer = null;
    }
  },
  methods: {
    change() {
      this.viewModel = { ...this.viewModel };
    },
    initEffects() {
      let vm = this;
      const viewer = this.viewer;

      if (!viewer.scene.context.depthTexture) {
        window.alert('This browser does not support the fog post process.');
      }

      // var tileset = new Cesium.Cesium3DTileset({
      //   url: Cesium.IonResource.fromAssetId(40866) //模型数据无法加载
      // });

      // viewer.scene.primitives.add(tileset);

      viewer.scene.camera.setView({
        destination: new Cesium.Cartesian3(1216356.033078094, -4736402.278325668, 4081270.375520902),
        orientation: new Cesium.HeadingPitchRoll(0.08033365594766728, -0.29519015695063455, 0.00027759141518046704),
        endTransform: Cesium.Matrix4.IDENTITY
      });

      // var ellipsoid = viewer.scene.globe.ellipsoid;

      // // Simple stage to change the color
      // var fragmentShaderSource =
      //   'uniform sampler2D colorTexture;\n' +
      //   'varying vec2 v_textureCoordinates;\n' +
      //   'uniform float scale;\n' +
      //   'uniform vec3 offset;\n' +
      //   'void main() {\n' +
      //   '    vec4 color = texture2D(colorTexture, v_textureCoordinates);\n' +
      //   '    gl_FragColor = vec4(color.rgb * scale + offset, 1.0);\n' +
      //   '}\n';

      // viewer.scene.postProcessStages.add(
      //   new Cesium.PostProcessStage({
      //     fragmentShader: fragmentShaderSource,
      //     uniforms: {
      //       scale: ()=>1,
      //       offset: function() {
      //         return new Cesium.Cartesian3(0.1, 0.2, 0.5);
      //       }
      //     }
      //   })
      // );

      // return; //模型数据无法加载

      var fragmentShaderSource =
        'float getDistance(sampler2D depthTexture, vec2 texCoords){ \n' +
        '    float depth = czm_unpackDepth(texture2D(depthTexture, texCoords)); \n' +
        '    if (depth == 0.0) { \n' +
        '        return czm_infinity; \n' +
        '    } \n' +
        '    vec4 eyeCoordinate = czm_windowToEyeCoordinates(gl_FragCoord.xy, depth); \n' +
        '    return -eyeCoordinate.z / eyeCoordinate.w; \n' +
        '} \n' +
        'float interpolateByDistance(vec4 nearFarScalar, float distance){ \n' +
        '    float startDistance = nearFarScalar.x; \n' +
        '    float startValue = nearFarScalar.y; \n' +
        '    float endDistance = nearFarScalar.z; \n' +
        '    float endValue = nearFarScalar.w; \n' +
        '    float a = clamp((distance - startDistance) / (endDistance - startDistance), 0.0, 1.0); \n' +
        '    return mix(startValue, endValue, a); \n' +
        '} \n' +
        'vec4 alphaBlend(vec4 finalFogColor, vec4 sceneColor){ \n' +
        '    return finalFogColor * vec4(finalFogColor.aaa, 1.0) + sceneColor * (1.0 - finalFogColor.a); \n' +
        '} \n' +
        'uniform sampler2D colorTexture; \n' +
        'uniform sampler2D depthTexture; \n' +
        'uniform vec4 fogByDistance; \n' +
        'uniform vec4 fogColor; \n' +
        'varying vec2 v_textureCoordinates; \n' +
        'void main(void){ \n' +
        '    float distance = getDistance(depthTexture, v_textureCoordinates); \n' +
        '    vec4 sceneColor = texture2D(colorTexture, v_textureCoordinates); \n' +
        '    float blendAmount = interpolateByDistance(fogByDistance, distance); \n' +
        '    vec4 finalFogColor = vec4(fogColor.rgb, fogColor.a * blendAmount); \n' +
        '    gl_FragColor = alphaBlend(finalFogColor, sceneColor); \n' +
        '} \n';

      const fogByDistance = new Cesium.Cartesian4(10, 0.0, 50000, 1.0);
      const fogColor = Cesium.Color.WHITE;
      const stage = new Cesium.PostProcessStage({
        fragmentShader: fragmentShaderSource,
        uniforms: {
          fogByDistance,
          fogColor
        }
      });

      var postProcessStage = viewer.scene.postProcessStages.add(stage);
    },

    onViewerInited(viewer) {
      let vm = this;
      new MousePosition(viewer, pos => {
        vm.nowPostion = pos;
      });
    },

    initViewer() {
      let vm = this;
      // Cesium.Ion.defaultAccessToken = $accessToken.cs;

      let osm = new Cesium.OpenStreetMapImageryProvider({
        url: 'https://a.tile.openstreetmap.org/'
      });
      let viewer = new Cesium.Viewer('cesium-drawer', {
        imageryProvider: osm,
        terrainProvider: Cesium.createWorldTerrain({
          // requestVertexNormals: true //Needed to visualize slope
        }),
        contextOptions: {
          webgl: {
            alpha: true
          }
        },
        selectionIndicator: false,
        // shadows: true,
        // terrainShadows: Cesium.ShadowMode.ENABLED,
        animation: false, //是否显示动画控件
        baseLayerPicker: false, //是否显示图层选择控件
        geocoder: false, //是否显示地名查找控件
        timeline: false, //是否显示时间线控件
        sceneModePicker: false, //是否显示投影方式控件
        navigationHelpButton: false, //是否显示帮助信息控件
        infoBox: false, //是否显示点击要素之后显示的信息
        fullscreenButton: false,
        shouldAnimate: true
      });

      // viewer.scene.globe.depthTestAgainstTerrain = true;

      this.viewer = viewer;
      this.onViewerInited(viewer);

      this.initEffects();

      // this.viewer.flyTo(this.viewer.entities);
    },

    onClick(value) {
      switch (value) {
        case 'play':
          this.stratPlay();
          break;
        case 'stop':
          this.stopPlay();
          break;
      }
    },

    stratPlay() {
      const viewer = this.viewer;
      if (((viewer.clock.shouldAnimate = !0), this.stopTime)) {
        viewer.clock.currentTime = this.stopTime;
      } else {
        // var e = '2019-06-18';
        const t = new Date(),
          i = '00',
          a = '24',
          r = new Date(new Date(t).setHours(Number(i))),
          o = new Date(new Date(t).setHours(Number(a)));
        (viewer.scene.globe.enableLighting = !0),
          (viewer.shadows = !0),
          (viewer.clock.startTime = Cesium.JulianDate.fromDate(r)),
          (viewer.clock.currentTime = Cesium.JulianDate.fromDate(r)),
          (viewer.clock.stopTime = Cesium.JulianDate.fromDate(o)),
          (viewer.clock.clockRange = Cesium.ClockRange.LOOP_STOP),
          (viewer.clock.clockStep = Cesium.ClockStep.SYSTEM_CLOCK_MULTIPLIER),
          (viewer.clock.multiplier = 1600);
      }
    },

    stopPlay() {
      const viewer = this.viewer;
      (this.stopTime = viewer.clock.currentTime), (viewer.clock.shouldAnimate = !1);
    }
  }
});
</script>

<style lang="less">
.cesium-draw {
  position: relative;
  width: 100%;
  height: 100%;
  overflow: hidden;
  color: white;
  font-size: 14px;

  #cesium-drawer {
    width: 100%;
    height: 100%;
    overflow: hidden;
    .cesium-viewer-bottom {
      display: none !important;
    }
  }

  .mouse-postion {
    position: absolute;
    bottom: 10px;
    right: 10px;
    font-size: 14px;
    padding: 8px 12px;
    line-height: 16px;
    color: white;
    z-index: 9999;
    background-color: rgba(40, 48, 60, 1);
    border-radius: 3px;
    opacity: 0.8;
  }
}

.chart-container {
  position: absolute;
  bottom: 7px;
  left: 7px;
  background-color: rgba(0, 0, 0, 0.5);

  #profileChart {
    width: 600px;
    height: 300px;
  }
}
#canvas-a {
  top: 10px;
  display: none;
}

#canvas-b {
  top: 120px;
  display: none;
}

.tool-box {
  position: absolute;
  top: 70px;
  left: 10px;
  z-index: 9;

  #menu {
    padding-top: 20px;
    button {
      background-color: rgba(0, 0, 0, 0.75);
      border-color: rgba(0, 0, 0, 0);
      cursor: pointer;
      transition: all 500ms;
      &:hover {
        opacity: 0.75;
      }
    }
  }

  .slider-box-wrapper {
    width: 18em;
    padding: 0 10px;
    background-color: rgba(0, 0, 0, 0.75);
    margin-bottom: 10px;
  }

  .select-box-wrapper {
    padding: 5px 15px;
    background-color: rgba(0, 0, 0, 0.75);
    margin-bottom: 10px;
    width: auto;
  }
}
</style>
